<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>提现记录</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    }
    body {
      background: #f5f7fa;
    }
    .withdraw-header {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 44px;
      position: relative;
      border-bottom: 1px solid #eee;
      background-color: #fff;
    }

    .back-btn {
      text-decoration: none;
      color: #000;
      font-size: 20px;
      position: absolute;
      left: 15px;
    }

    .title-text {
      font-size: 17px;
      font-weight: bold;
      color: #000;
    }
    .container {
      max-width: 500px;
      margin: 0 auto;
      background: #fff;
      min-height: 100vh;
    }
    .header {
      padding: 16px;
      border-bottom: 1px solid #eee;
      font-size: 18px;
      font-weight: 600;
      color: #333;
      position: relative;
      text-align: center;
    }
    .back-btn {
      text-decoration: none;
      color: #000;
      font-size: 20px;
      position: absolute;
      left: 15px;
    }
    .record-item {
      padding: 16px;
      border-bottom: 1px solid #eee;
      display: flex;
      flex-direction: column;
      gap: 8px;
    }
    .record-title {
      font-size: 15px;
      color: #333;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .record-title span {
      color: #f39c12;
      font-weight: 500;
    }
    .record-info {
      font-size: 14px;
      color: #666;
      line-height: 1.6;
    }
    .record-info span {
      color: #f39c12;
    }
  </style>
</head>
<body>
<div class="container">
  <div class="withdraw-header">
    <a href="index.html" class="back-btn">&#60;</a>
    <span class="title-text">提现记录</span>
  </div>
  <div id="record-list"></div>
</div>

<script>
  let withdrawalRecords = [];
  let chargeData = {}; // 存储chargeData数据

  initRecords();

  // 初始化数据
  function initRecords() {
    // 初始化提现记录
    const storedRecords = localStorage.getItem('withdrawalRecords');
    if (storedRecords) {
      withdrawalRecords = JSON.parse(storedRecords);
    } else {
      withdrawalRecords = [
        {
          amount: 14369.41,
          accountHolder: "李峰杰",
          bankCard: "6226228303314983",
          bankName: "中国民生银行股份有限公司济宁任城支行",
          phone: "15623454988",
          time: "2025-06-20 09:39:52",
          status: "已打款",
          orderNo: "TX20250620939001"
        },
        {
          amount: 21376.94,
          accountHolder: "李峰杰",
          bankCard: "6226228303314983",
          bankName: "中国民生银行股份有限公司济宁任城支行",
          phone: "15623454988",
          time: "2025-07-20 09:08:36",
          status: "已打款",
          orderNo: "TX20250720908002"
        }
      ];
      saveRecords();
    }

    // 初始化chargeData
    initChargeData();

    // 渲染记录并更新chargeData
    renderRecords();
    updateChargeData();

    // 页面初始化时执行一次检查
    checkAndGenerateRecord();
  }

  // 初始化chargeData
  function initChargeData() {
    const storedChargeData = localStorage.getItem('chargeData');
    if (storedChargeData) {
      chargeData = JSON.parse(storedChargeData);
    } else {
      // 初始值（totalIncome可根据实际业务场景调整初始值）
      chargeData = {
        totalIncome: 35746.35,        // 总收入
        withdrawnTotal: 35746.35,     // 已提现总金额
        withdrawableAmount: 0.00  // 可提现金额（totalIncome + 已提现总金额）
      };
    }
  }

  // 保存记录到本地存储
  function saveRecords() {
    localStorage.setItem('withdrawalRecords', JSON.stringify(withdrawalRecords));
  }

  // 保存chargeData到本地存储
  function saveChargeData() {
    localStorage.setItem('chargeData', JSON.stringify(chargeData));
  }

  // 计算已提现总金额
  function getWithdrawnTotal() {
    return withdrawalRecords.reduce((total, record) => {
      // 只计算状态为"已打款"的记录
      if (record.status === "已打款") {
        return total + parseFloat(record.amount);
      }
      return total;
    }, 0);
  }

  // 更新chargeData计算
  function updateChargeData() {
    const withdrawnTotal = getWithdrawnTotal();
    chargeData.withdrawnTotal = parseFloat(withdrawnTotal.toFixed(2));
    // 计算可提现金额 = 总收入 + 已提现总金额
    chargeData.withdrawableAmount = parseFloat(
            (parseFloat(chargeData.totalIncome) + chargeData.withdrawnTotal).toFixed(2)
    );
    saveChargeData();
    console.log('更新后的chargeData:', chargeData);
  }

  // 渲染记录
  function renderRecords() {
    const sortedRecords = [...withdrawalRecords].sort((a, b) => {
      return new Date(b.time) - new Date(a.time);
    });

    const list = document.getElementById("record-list");
    list.innerHTML = "";

    sortedRecords.forEach(record => {
      const item = document.createElement("div");
      item.className = "record-item";
      item.innerHTML = `
          <div class="record-title">
            <span>提现单号: ${record.orderNo}</span>
            <span>${record.status}</span>
          </div>
          <div class="record-info">
            <p>提现金额：<span>¥${parseFloat(record.amount).toFixed(2)}</span></p>
            <p>开户人：<span>${record.accountHolder}</span></p>
            <p>银行卡号：<span>${record.bankCard}</span></p>
            <p>银行名称：<span>${record.bankName}</span></p>
            <p>联系电话：<span>${record.phone}</span></p>
            <p>提现时间：<span>${record.time}</span></p>
          </div>
        `;
      list.appendChild(item);
    });
  }

  function checkAndGenerateRecord() {
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth() + 1;
    const currentDate = now.getDate();

    console.log('执行一次检查，当前日期：', `${currentYear}-${currentMonth}-${currentDate}`);

    // 获取现有记录中最新的月份
    let latestYear = 2025;
    let latestMonth = 6;
    if (withdrawalRecords.length > 0) {
      const latestRecord = [...withdrawalRecords].sort((a, b) => new Date(b.time) - new Date(a.time))[0];
      const latestRecordDate = new Date(latestRecord.time);
      latestYear = latestRecordDate.getFullYear();
      latestMonth = latestRecordDate.getMonth() + 1;
    }

    // 补全每个月20号的记录
    let year = latestYear;
    let month = latestMonth + 1;

    while (
            (year < currentYear) ||
            (year === currentYear && month <= currentMonth)
            ) {
      if (month > 12) {
        month = 1;
        year++;
      }

      // 检查该月是否已有20号记录
      const hasRecord = withdrawalRecords.some(record => {
        const recordDate = new Date(record.time);
        return (
                recordDate.getFullYear() === year &&
                recordDate.getMonth() + 1 === month &&
                recordDate.getDate() === 20
        );
      });

      if (!hasRecord) {
        // 判断是否为当前月份且未到20号
        const isCurrentMonth = year === currentYear && month === currentMonth;
        const isBefore20th = currentDate < 20;

        if (isCurrentMonth && isBefore20th) {
          console.log(`当前月份${currentMonth}月，日期${currentDate}（未到20号），暂不生成20号记录`);
          // 1. 读取并解析localStorage中的chargeData
          const chargeDataStr = localStorage.getItem('chargeData');
          const chargeData = JSON.parse(chargeDataStr || '{}');
          const currentDeviceCount = chargeData.deviceCount;
          console.log('跳转前当前存储的设备数：', currentDeviceCount);

          month++;
          continue;
        }

        // 生成随机时间
        const isToday20 = (year === currentYear && month === currentMonth && currentDate === 20);
        const randomTime = getRandomTime(isToday20, now);
        const recordTime = `${year}-${String(month).padStart(2, '0')}-20 ${randomTime}`;
        const dt = new Date(recordTime);


        const newRecord = {
          amount: (Math.random() * 7000 + 21000).toFixed(2),
          accountHolder: "李峰杰",
          bankCard: "6226228303314983",
          bankName: "中国民生银行股份有限公司济宁任城支行",
          phone: "15623454988",
          time: recordTime,
          status: "已打款",
          orderNo: `TX${dt.getFullYear()}${String(dt.getMonth() + 1).padStart(2, '0')}${String(dt.getDate()).padStart(2, '0')}${String(dt.getHours()).padStart(2, '0')}${String(dt.getMinutes()).padStart(2, '0')}${String(dt.getSeconds()).padStart(2, '0')}`
        };

        withdrawalRecords.push(newRecord);
        console.log(`补全${year}-${month}月20号的记录：`, newRecord);
      }

      month++;
    }

    // 渲染并保存记录，同时更新chargeData
    renderRecords();
    saveRecords();
    updateChargeData(); // 新增记录后更新chargeData
  }

  /**
   * 生成随机时间
   * @param {boolean} isToday - 是否是20号当天
   * @param {Date} currentTime - 当前时间
   * @returns {string} 格式化的时间字符串（HH:MM:SS）
   */
  function getRandomTime(isToday, currentTime) {
    let maxHours = 23;
    let maxMinutes = 59;
    let maxSeconds = 59;

    if (isToday) {
      maxHours = currentTime.getHours();
      maxMinutes = currentTime.getMinutes();
      maxSeconds = currentTime.getSeconds();
    }

    const hours = Math.floor(Math.random() * (maxHours + 1));
    const minutes = hours < maxHours
            ? Math.floor(Math.random() * 60)
            : Math.floor(Math.random() * (maxMinutes + 1));
    const seconds = (hours < maxHours || minutes < maxMinutes)
            ? Math.floor(Math.random() * 60)
            : Math.floor(Math.random() * (maxSeconds + 1));

    return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
  }


</script>
</body>
</html>